#include <QDebug>

#include "yuvloader.h"

YUVLoader::YUVLoader(QObject *parent)
    : QObject(parent),
      m_file("../VideoOutput/test_yuv420p_320x180.yuv"),
      m_stream(&m_file)
{
    if(!m_file.open(QIODevice::ReadOnly)){
        qDebug() << "open file failed:" << m_file.errorString();
    }
    connect(&m_frameTimer, &QTimer::timeout, this, &YUVLoader::onFrameTimer);
    m_frameTimer.start(33);
}

void YUVLoader::onFrameTimer() {
    int width = 320;
    int height = 180;
    const int frameSize = int(320*180*1.5);

    if (m_stream.device()->bytesAvailable() < frameSize) {
        m_stream.device()->seek(0);
    }

    YUVData yuvData;
    yuvData.Y.resize(width * height);
    m_stream.readRawData((char*)yuvData.Y.data(), yuvData.Y.size());
    yuvData.U.resize(width / 2 * height / 2);
    m_stream.readRawData((char*)yuvData.U.data(), yuvData.U.size());
    yuvData.V.resize(width / 2 * height / 2);
    m_stream.readRawData((char*)yuvData.V.data(), yuvData.V.size());
    yuvData.yLineSize = width;
    yuvData.uLineSize = width/2;
    yuvData.vLineSize = width/2;
    yuvData.height = height;

    emit newFrameAvailable(yuvData);
}

YUVLoader::~YUVLoader() {
    m_file.close();
}
